<?php

class Product extends AppModel {

    var $name = 'Product';

    /**
     * ขนาดรูปภาพ (barcode และ picture 1, 2)
     * ไม่เกิน 50 KB
     */
    const PICTURE_SIZE_LIMIT = 51200;

    var $displayField = 'part_no';
    var $order = 'Product.id DESC';
    var $belongsTo = array(
        'Category' => array(
            'fields' => array('code', 'name')
        ),
        'Supplier' => array(
            'fields' => array('code', 'name', 'special_part_no')
        ),
        'Brand' => array(
            'fields' => array('name')
        ),
        'ItsType' => array(
            'foreignKey' => 'type_id',
            'fields' => array('code', 'name')
        ),
        'Unit' => array(
            'fields' => array('title')
        ),
        'User' => array(
            'foreignKey' => 'collector_id',
            'fields' => array('name')
        ),
        'LastDispatchCustomer' => array(
            'className' => 'Customer',
            'foreignKey' => 'last_dispatch_customer_id',
        ),
    );
    var $validate = array(
        'part_no' => array(
            'notEmpty' => array(
                'rule' => array('notEmpty'),
                'message' => 'Part no is required.',
                'required' => true,
                'on' => 'create'
            ),
            'isUnique' => array(
                'rule' => 'isUnique',
                'message' => 'This part no is already taken.',
            ),
        ),
        'supplier_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Supplier is required.',
            'required' => true,
            'on' => 'create'
        ),
        'title' => array(
            'rule' => 'notEmpty',
            'message' => 'Product title is required.',
            'required' => true,
            'on' => 'create'
        ),
        'text' => array(
            'rule' => 'notEmpty',
            'message' => 'Product description is required.',
            'required' => true,
            'on' => 'create'
        ),
        'brand_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Brand is required.',
            'required' => true,
            'on' => 'create'
        ),
        'model' => array(
            'rule' => 'notEmpty',
            'message' => 'Model is required.',
            'required' => true,
            'on' => 'create'
        ),
        'unit_id' => array(
            'rule' => 'notEmpty',
            'message' => 'Unit is required.',
            'required' => true,
            'on' => 'create'
        ),
        'current_stock' => array(
            'rule' => 'numeric',
            'message' => 'Current stock must be a number.',
            'allowEmpty' => true
        ),
        'price' => array(
            'rule' => 'numeric',
            'message' => 'Price must be a number.',
            'allowEmpty' => true
        ),
    );
    var $hasMany = array('ProductPriceHistory', 'CustProductSite');

    function beforeSave() {
        // remove , ออกจาก price
        if (isset($this->data['Product']['cost'])) {
            $this->data['Product']['cost'] = str_replace(',', '', $this->data['Product']['cost']);
        }
        if (isset($this->data['Product']['price'])) {
            $this->data['Product']['price'] = str_replace(',', '', $this->data['Product']['price']);
        }
        return true;
    }

    function afterFind($results) {
        foreach ($results as &$p) {
            if (isset($p['Product'])) {
                if (isset($p['Product']['last_stock_in_date'])) {
                    $p['Product']['last_stock_in_date'] = $this->dateFormatAfterFind($p['Product']['last_stock_in_date']);
                }
                if (isset($p['Product']['last_dispatch_date'])) {
                    $p['Product']['last_dispatch_date'] = $this->dateFormatAfterFind($p['Product']['last_dispatch_date']);
                }
            }
        }
        return $results;
    }

    function afterSave($created) {
        // inserted 
        if ($created) {
            $this->ProductPriceHistory->save($this->id, 'cost', $this->data['Product']['cost'], $this->data['Product']['collector_id']);
            $this->ProductPriceHistory->save($this->id, 'price', $this->data['Product']['price'], $this->data['Product']['collector_id']);
        } else {
            //updated
            $this->_updatePriceHistory('cost');
            $this->_updatePriceHistory('price');
        }
    }

    function _updatePriceHistory($type) {
        if (!empty($this->data['Product'][$type])) {

            $priceHistory = $this->ProductPriceHistory->find('first', array(
                        'conditions' => array(
                            'product_id' => $this->id,
                            'type' => $type
                        ),
                        'order' => 'created DESC',
                        'contain' => array()
                    ));

            // มีการ update ราคาใน Product ล่าสุด ไม่เท่ากับใน history
            if ($priceHistory == null || ($priceHistory['ProductPriceHistory']['price'] != $this->field($type))) {
                $this->ProductPriceHistory->save($this->id, $type, $this->data['Product'][$type], $this->field('collector_id'));
            }
        }
    }
}